import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:lishi/global.dart';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:lishi/api.dart';
import 'package:lishi/calendar_modal.dart';
import 'package:lishi/page.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: '历史的今天',
      theme: ThemeData(
        primarySwatch: Colors.brown,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(title: '历史的今天'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);
  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  var _data;

  @override
  void initState() {
    getData(DateTime.now());
    super.initState();
  }

  getData(date) async {
    var str = ['一', '二', '三', '四', '五', '六', '日'];
    var strEn = [
      'Monday',
      'Tuesday',
      'Wednesday',
      'Thursday',
      'Friday',
      'Saturday',
      'Sunday'
    ];
    var _date = DateFormat('yyyy年MM月dd日').format(date);
    var _month = date.month;
    var _day = date.day;
    var _weekday = str[date.weekday - 1];
    var _weekdayEn = strEn[date.weekday - 1];
    if (_data != null) EasyLoading.show();
    var res = await lishi(_month, _day);
    if (_data != null) EasyLoading.dismiss();
    setState(() {
      _data = {
        'list': res['result'],
        'day': _day,
        'date': _date,
        'weekday': _weekday,
        'weekdayEn': _weekdayEn,
      };
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(
          widget.title,
          style: TextStyle(
            color: Global.fontColor,
            fontSize: 12,
            fontWeight: FontWeight.bold,
          ),
        ),
        backgroundColor: Global.backgroundColor,
        brightness: Brightness.light,
        elevation: 0,
        actions: <Widget>[
          IconButton(
            icon: Icon(
              Icons.date_range,
              color: Global.fontColor,
              size: 19,
            ),
            tooltip: '日历',
            onPressed: () {
              CalendarModal.show(
                context: context,
                date: DateTime.now(),
                onChange: (date) {
                  getData(date);
                },
              );
            },
          )
        ],
      ),
      body: Container(
        height: MediaQuery.of(context).size.height,
        color: Global.backgroundColor,
        child: FlutterEasyLoading(
          child: SingleChildScrollView(
            child: ContentPage(data: _data),
          ),
        ),
      ),
    );
  }
}
